package com.dms.wuziqi.controller;

import com.dms.wuziqi.JwtUtil.JwtUtil;
import com.dms.wuziqi.JwtUtil.JwtUtil2;
import com.dms.wuziqi.Result.Result;
import com.dms.wuziqi.fliter.Role;
import com.dms.wuziqi.pojo.User;
import com.dms.wuziqi.service.UserService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin(origins = "*")
public class UserController {
    @Autowired
    UserService userService;

    @GetMapping("/getUserById")
    public Result getUserById(@RequestParam(name = "userId") int id){
        User user=userService.findUserById(id);
        System.out.println(user);
        return Result.success(user);
    }
    @GetMapping("/getUserByToken")
    public Result getUserById(@RequestHeader(name = "Authorization")String token){
        Map<String,Object> claim=new HashMap<>();
        claim=JwtUtil2.parseToken(token);
        int UserId= (int) claim.get("userId");
        User user=userService.findUserById(UserId);
        return Result.success(user);
    }
    @PostMapping("/userLogin")
    public Result userLogin(@RequestBody User user){
        System.out.println(user);
        User user1=userService.findUserByNameAndPwd(user.getUserName(), user.getUserPwd());
        if (user1!=null){
            Map<String,Object> claims=new HashMap<>();
            claims.put("userId",user1.getUserId());
            claims.put("role","user");
            String token=JwtUtil2.genToken(claims);
            return Result.success(token);
        }else {
            return Result.error("登陆失败，请检查");
        }
    }
    @PostMapping("/userRes")
    public Result userRes(@RequestBody User user){
        userService.insertUser(user.getUserName(), user.getUserPwd());
        return Result.success("操作添加用户");
    }
   @GetMapping("/getLoanList")
    public Result getLoanList(@RequestParam(name = "userId")int id){

return Result.success();
   }
}
